package com.videoaggre.zcl.ui.fragment.enterdesk

import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.videoaggre.zcl.R
import com.videoaggre.zcl.databinding.ViewTabHornBinding
import com.videoaggre.zcl.ui.adapter.ViewPage2Adapter
import com.videoaggre.zcl.ui.fragment.BaseFragment
import kotlinx.android.synthetic.main.enterdesk_fragment_main.*

class EnterdeskFragment : BaseFragment(R.layout.enterdesk_fragment_main), TabLayout.OnTabSelectedListener {
    private val tabs = arrayOf("推荐", "分类", "品牌", "分辨率")
    private val fragments = mutableListOf<Fragment>().apply {
        add(EnterdeskImageFragment())
        add(EnterdeskClassifyFragment())
        add(EnterdeskBrandFragtment())
        add(EnterdeskResolutionFragtment())
    }

    override fun initView(rootView: View?, savedInstanceState: Bundle?) {
        tabLayout.addOnTabSelectedListener(this)
        tabs.forEachIndexed { index, s ->
            tabLayout.addTab(tabLayout.newTab().setCustomView(ViewTabHornBinding.inflate(layoutInflater).let {
                it.root.tag = it
                it.tvText.text = tabs[index]
                it.root
            }))
        }
        viewPager.adapter = ViewPage2Adapter(childFragmentManager, lifecycle, fragments)
        viewPager.offscreenPageLimit = tabs.size
        viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                tabLayout.selectTab(tabLayout.getTabAt(position))
                //tabLayout.post { tabLayout.setScrollPosition(position, 0f, true) }
            }
        })
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        (tab?.customView?.tag as? ViewTabHornBinding)?.run {
            tvText.textSize = 20f
            tvText.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
        }
        viewPager.currentItem = tab?.position ?: 0
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
        (tab?.customView?.tag as? ViewTabHornBinding)?.run {
            tvText.textSize = 15f
            tvText.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
        }
    }

    override fun onTabReselected(tab: TabLayout.Tab?) {

    }
}